<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="70%"
    title="查看"
    :dialog-style="{ top: '20px' }"
    :footer="null"
  >
    <div v-if="visible" v-permission="['base-data:make:query']" v-loading="loading">
      <a-descriptions :column="4" :label-style="{ width: '100px' }" bordered>
        <a-descriptions-item label="制作名称" :span="4">
          {{ formData.name }}
        </a-descriptions-item>
        <a-descriptions-item label="制作描述" :span="4">
          {{ formData.description }}
        </a-descriptions-item>
        <a-descriptions-item label="状态" :span="4">
          <available-tag :available="formData.available" />
        </a-descriptions-item>
      </a-descriptions>
      <vxe-grid
        resizable
        show-overflow
        :show-footer="true"
        highlight-hover-row
        keep-source
        row-id="id"
        :expand-config="{ expandAll: true }"
        :columns="materialTableColumn"
        :toolbar-config="toolbarConfig"
        :data="formData.materials"
        :footer-data="footerData"
        :height="450"
        :scroll-y="{
          enabled: true,
          gt: 0,
        }"
      >
        <!-- 原料名称 -->
        <template #productName_default="{ rowIndex, row }">
          <a-form-item :name="['materials', rowIndex, 'productId']" no-style required>
            <product-selector
              :disabled="true"
              v-model:value="row.productId"
              :request-params="{
                productType: [1, 4].join(','),
              }"
              @input-row="
                (data) => {
                  row.code = data?.code;
                  row.skuCode = data?.skuCode;
                  row.spec = data?.spec;
                  row.consumeUnitId = data?.unit;
                  row.consumeNum = null;
                  row.consumeCost = null;
                  calcCost(row);
                }
              "
              @load-complete="
                (data) => {
                  $nextTick(() => {
                    row.code = data[0]?.code;
                    row.skuCode = data[0]?.skuCode;
                    row.spec = data[0]?.spec;
                    calcCost(row);
                  });
                }
              "
            />
          </a-form-item>
        </template>
        <!-- 消耗单位 -->
        <template #consumeUnit_default="{ rowIndex, row }">
          <a-form-item :name="['materials', rowIndex, 'consumeUnitId']" no-style required>
            <product-unit-select
              v-model:value="row.consumeUnitId"
              :product-id="row.productId"
              :disabled="true"
              @change="calcCost(row)"
            />
          </a-form-item>
        </template>
        <!-- 消耗数量 -->
        <template #consumeNum_default="{ rowIndex, row }">
          <a-form-item :name="['materials', rowIndex, 'consumeNum']" no-style required>
            <a-input-number
              v-model:value="row.consumeNum"
              min="0"
              :precision="4"
              :disabled="true"
              @change="calcCost(row)"
            />
          </a-form-item>
        </template>
        <!-- 消耗成本 -->
        <template #consumeCost_default="{ rowIndex, row }">
          <a-form-item :name="['materials', rowIndex, 'consumeCost']" no-style required>
            <a-input-number
              style="width: calc(100% - 50px)"
              v-model:value="row.consumeCost"
              min="0"
              :precision="6"
              :disabled="true"
            />
          </a-form-item>
        </template>

        <!-- 替代品 -->
        <template #replacements_default="{ rowIndex, row }">
          <a-card>
            <vxe-grid
              resizable
              show-overflow
              highlight-hover-row
              keep-source
              row-id="id"
              :expand-config="{ expandAll: true }"
              :columns="materialTableColumn.filter((item) => item.type !== 'expand')"
              :toolbar-config="toolbarConfig"
              :data="row.replacements"
              :height="200"
            >
              <!-- 原料名称 -->
              <template #productName_default="data">
                <a-form-item
                  :name="['materials', rowIndex, 'replacements', data.rowIndex, 'productId']"
                  no-style
                  required
                >
                  <product-selector
                    :disabled="true"
                    v-model:value="data.row.productId"
                    :request-params="{
                      productType: [1, 4].join(','),
                    }"
                    @input-row="
                      (rowData) => {
                        data.row.code = rowData?.code;
                        data.row.skuCode = rowData?.skuCode;
                        data.row.spec = rowData?.spec;
                        data.row.consumeUnitId = rowData?.unit;
                        data.row.consumeNum = null;
                        data.row.consumeCost = null;
                        calcCost(row);
                      }
                    "
                    @load-complete="
                      (rowData) => {
                        $nextTick(() => {
                          data.row.code = rowData[0]?.code;
                        });
                      }
                    "
                  />
                </a-form-item>
              </template>
              <!-- 消耗单位 -->
              <template #consumeUnit_default="data">
                <a-form-item
                  :name="['materials', rowIndex, 'replacements', data.rowIndex, 'consumeUnitId']"
                  no-style
                  required
                >
                  <product-unit-select
                    v-model:value="data.row.consumeUnitId"
                    :product-id="data.row.productId"
                    :disabled="true"
                    @change="calcCost(data.row)"
                  />
                </a-form-item>
              </template>
              <!-- 消耗数量 -->
              <template #consumeNum_default="data">
                <a-form-item
                  :name="['materials', rowIndex, 'replacements', data.rowIndex, 'consumeNum']"
                  no-style
                  required
                >
                  <a-input-number
                    v-model:value="data.row.consumeNum"
                    min="0"
                    :precision="4"
                    :disabled="true"
                    @change="calcCost(data.row)"
                  />
                </a-form-item>
              </template>
              <!-- 消耗成本 -->
              <template #consumeCost_default="data">
                <a-form-item
                  :name="['materials', rowIndex, 'replacements', data.rowIndex, 'consumeNum']"
                  no-style
                  required
                >
                  <a-input-number
                    style="width: calc(100% - 50px)"
                    v-model:value="data.row.consumeCost"
                    min="0"
                    :precision="6"
                    :disabled="true"
                  />
                </a-form-item>
              </template>
            </vxe-grid>
          </a-card>
        </template>
      </vxe-grid>
    </div>
  </a-modal>
</template>
<script>
  import { defineComponent } from 'vue';
  import * as api from '@/api/base-data/make';
  import * as productApi from '@/api/base-data/product/info';
  import ProductSelector from '@/components/Selector/src/ProductSelector.vue';
  import ProductUnitSelect from '@/views/base-data/unit/product-unit-select/index.vue';
  import AvailableTag from '@/components/Tag/src/AvailableTag.vue';

  export default defineComponent({
    // 使用组件
    components: { AvailableTag, ProductUnitSelect, ProductSelector },
    props: {
      id: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        // 是否可见
        visible: false,
        // 是否显示加载框
        loading: false,
        // 表单数据
        formData: {},
        //
        materialTableColumn: [
          {
            title: '替代',
            type: 'expand',
            field: 'expand',
            width: 80,
            align: 'center',
            slots: { content: 'replacements_default' },
          },
          {
            field: 'type',
            title: '类别',
            width: 80,
            formatter: ({ cellValue }) => (cellValue === 0 ? '主材料' : '替代材料'),
          },
          {
            field: 'productName',
            title: '原料名称',
            minWidth: 160,
            slots: { default: 'productName_default' },
          },
          { field: 'code', title: '原料编码', width: 100 },
          { field: 'skuCode', title: '原料SKU', width: 100 },
          { field: 'spec', title: '原料规格', minWidth: 120 },
          {
            field: 'consumeUnitId',
            title: '消耗单位',
            width: 100,
            slots: { default: 'consumeUnit_default' },
          },
          {
            field: 'consumeNum',
            title: '消耗数量',
            width: 120,
            slots: { default: 'consumeNum_default' },
          },
          {
            field: 'consumeCost',
            title: '成本价',
            minWidth: 140,
            slots: { default: 'consumeCost_default' },
          },
        ],
        toolbarConfig: {
          zoom: false,
          refresh: false,
          custom: false,
          // 自定义左侧工具栏
          slots: {
            buttons: 'toolbar_buttons',
          },
        },
        footerData: [
          {
            expand: '合计',
            type: '-',
            productName: '',
            code: '',
            skuCode: '',
            spec: '',
            consumeUnitId: '',
            consumeNum: 0,
            consumeCost: 0,
          },
        ],
      };
    },
    watch: {
      'formData.materials': {
        handler() {
          this.calcSum();
        },
        deep: true,
      },
    },
    created() {
      this.initFormData();
    },
    methods: {
      // 打开对话框 由父页面触发
      openDialog() {
        this.visible = true;

        this.$nextTick(() => this.open());
      },
      // 关闭对话框
      closeDialog() {
        this.visible = false;
        this.$emit('close');
      },
      // 初始化表单数据
      initFormData() {
        this.formData = {
          name: '',
          description: '',
          materials: [],
        };
        this.calcSum();
      },
      // 页面显示时触发
      open() {
        // 初始化数据
        this.initFormData();

        // 查询数据
        this.loadFormData();
      },
      // 查询数据
      loadFormData() {
        this.loading = true;
        api
          .get(this.id)
          .then((data) => {
            this.formData = data;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 添加主材料
      addMaterial() {
        this.formData.materials.push({
          type: 0,
          productId: '',
          replacements: [],
        });
      },
      // 添加辅助材料
      addReplacement(rowIndex) {
        this.formData.materials[rowIndex].replacements.push({
          type: 1,
          productId: '',
        });
      },
      // 计算用量成本
      calcCost(row) {
        if (row && row.productId && row.consumeUnitId && row.consumeNum) {
          productApi
            .calcCost({
              productId: row.productId,
              unitId: row.consumeUnitId,
              num: row.consumeNum,
            })
            .then((res) => {
              row.consumeCost = res;
            });
        }
      },
      calcSum() {
        this.footerData[0].productName = this.formData.materials.length;
        this.footerData[0].consumeNum = this.formData.materials.reduce(
          (sum, item) => sum + (item?.consumeNum || 0),
          0,
        );
        this.footerData[0].consumeCost = this.formData.materials.reduce(
          (sum, item) => sum + (item.consumeCost || 0),
          0,
        );
      },
    },
  });
</script>
